package chatBot.controller;

import chatBot.config.AlipayConfig;
import chatBot.entity.Commodity;
import chatBot.entity.Order;
import chatBot.repository.CommodityRepository;
import chatBot.service.AliPayService;
import chatBot.service.OrderService;
import chatBot.service.UserService;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/gpt")
public class AlipayController {

    @Autowired
    private AliPayService alipayService;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CommodityRepository commodityRepository;

    @Autowired
    private UserService userService;

    @PostMapping("/createOrder")
    public String createOrder(@RequestBody HashMap<String,String> body) {
        String orderNo = String.valueOf(System.currentTimeMillis());
        for (String key:body.keySet()){
            System.out.println(body.get(key));
        }

        Long userId = Long.valueOf(body.get("userId"));
        Integer commodityType = Integer.parseInt(body.get("commodityType"));
        Commodity commodity = commodityRepository.findByCommodityType(commodityType).orElse(new Commodity());


        // 创建订单并保存订单信息
        String result = alipayService.createAlipayOrder(orderNo, commodity.getCommodityPrice());

        Order order = new Order();
        order.setOrderId(Long.valueOf(orderNo));
        order.setUserId(userId);
        order.setAmount(commodity.getCommodityPrice());
        order.setAmount(commodity.getCommodityPrice());
        order.setCommodityId(commodity.getCommodityId());
        order.setPayType(1);  // 支付类型：1表示支付宝
        order.setStatus(0);   // 订单状态：0表示未支付
        order.setCreateTime(new Date());
        orderService.saveOrder(order);

        return result;
    }

    @PostMapping("/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        log.info("支付回调触发");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }

        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(), "UTF-8", "RSA2");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (signVerified) {
            String outTradeNo = params.get("out_trade_no");
            String tradeStatus = params.get("trade_status");

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                orderService.updateOrderStatus(Long.valueOf(outTradeNo), 1, new Date());
                Order order = orderService.findOrderById(Long.valueOf(outTradeNo));
                Commodity commodity = commodityRepository.findByCommodityId(order.getCommodityId()).orElse(new Commodity());
                userService.addTokens(order.getUserId(), commodity.getTokens());
            } else {
                orderService.updateOrderStatus(Long.valueOf(outTradeNo), 2, new Date());
            }
            return "success";
        } else {
            return "fail";
        }
    }
}
